package cn.cjxy.springmvcdemo2.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class UploadController {
	@RequestMapping(value="/upload",method= RequestMethod.POST)
	public String uploadFile(MultipartFile fileUpload, String username, HttpServletRequest req) throws FileNotFoundException, IOException {
		
		System.out.println("普通表单获取方式：" + username);
		
		//上传表单信息：注意MultipartFile对象的名称必须与上传表单项的name属性值一致
		System.out.println("上传文件是否为空:" + fileUpload.isEmpty());
		System.out.println("上传文件的大小（字节）:" + fileUpload.getSize());
		System.out.println("上传文件的类型:" + fileUpload.getContentType());
		System.out.println("上传表单name属性值:" + fileUpload.getName());
		System.out.println("上传文件名:" + fileUpload.getOriginalFilename());

	// 获取upload真实路径:一大巨坑（uploadFile千万不要和请求upload一样的名字，否则第二次上传出现405）
        System.out.println(req.getServletContext());//  /webapps/ROOT/uploadFile
		String realPath = req.getServletContext().getRealPath("/uploadFile");
		File file = new File(realPath);
		if (!file.exists()) {// 如果upload文件夹不存在，就创建
			file.mkdirs();
		}


//使用UUID加前缀命名文件，防止名字重复被覆盖
		String fileName = fileUpload.getOriginalFilename();

		InputStream in= fileUpload.getInputStream();;//声明输入输出流
		OutputStream out=new FileOutputStream(new File(realPath+"\\"+fileName));//指定输出流的位置;

		//使用IOUtils.copy实现文件复制 
		IOUtils.copy(in, out);
		System.out.println("上传成功");
		in.close();
		out.close();
		return "redirect:/upload.jsp";
	}
}